import { array } from "jszip/lib/support";

//
export function jyxdPrint(printParam) {

  if (typeof printParam != "object") {
    alert("打印参数不正确!");
    return;
  }

  //border styles in new page
  const borderStyle = "1px solid #091020"////#091020";

  var tableId = ""; // table_id: 包含<table>或<el-table>的div的id,或者<table>或<el-table>本身的id,如"mytable"
  var titleId = ""; // title_id: 纸面大标题div的id,如"mytitle" or ""(空值表示无抬头)
  var tailId = ""; // tail_id: 纸面表后的签名栏，如"mytail" or ""(空值表示表后无签名栏)

  var titleType = 2; // 大标题放置方法，0 表示不放大标题, 1 表示仅第一页放, 2 表示所有页都放, title: "" or "first" or "首页"
  var tailType = 2; // 0 no tail, 1 for first page, 2 for all pages, tail: "" or "first" or "首页"
  var color = 0; //0: remove colors, color: "" or "color" or "彩色"
  var button = 0; //0: hide buttons, button: "" or "button"
  var pageList = new Array(); //page list to print, page_list: [0,1-5]
  var pageRows = 17; // 0 don't break page, >0 data rows per page, page_rows: 10
  var secondRows = pageRows; //data rows of the pages except the first one, if different, second_rows: 15
  var blank = 0; //0 not blank table, other is blank pages, blank: 0 or 10
  var hiddenCols = new Array(); //hidden columns list, hidden_cols:[0,2,3-5]
  var paperHeight = 0; //use paper height to break page? paper_height:"720", must be larger than 300
  var paperWidth = 1605;//屏幕缩放率150%下: A4横向宽度：无边距时1720  最小边距时1690  默认边距时1605。与像素分辨率无关
  var blankLineHeight = 40; //line height in blank pages, blank_line_height:"40" or empty
  var preview = 0; //0 send out to printer, 1 preview at the first,adding print buttons. preview:"预览"
  var paging = printParam.paging ? true : false; // true 显示第几页，false 不显示

  var avgWidth = 32;
  var colWidths = printParam.col_width;/*[
        { col: 0, width: 80 },
        { col: 1, width: 50 },
        { col: 14, width: 100 },
        { col: 30, width: 80 },
    ];*/
  var debuging = 1; //是否打印调试信息?
  //添加打印页码设置
  var startPage="";
  if(typeof printParam.pageStartNumber=="undefined" || printParam.pageStartNumber==''){
    startPage=1;
  }else{
    startPage=printParam.pageStartNumber;
  }

  var divideCols=new Array();  //单行内容允许拆分展示的列
  if(typeof printParam.divide_cols=="object")
    divideCols=printParam.divide_cols;

  //divs in new page
  var titleDiv;
  var tableDiv;
  var tailDiv;

  var eltable = 0; //if this is a el-table,1,0 not
  var firstRow = 0; //first data row number, 0 for all

  var headColIndexArray = new Array();

  var titleHeight = 0;
  var theadHeight = 0;
  var tfootHeight = 0;
  var tailHeight = 0;

  //id names in new page
  const titleDivId = "titleDivId";
  const tableDivId = "tableDivId";
  const tailDivId = "tailDivId";

  const theadId = "theadId"; //table header section's id
  const tbodyId = "tbodyId"; //table body section's id
  const tfootId = "tfootId"; //table foot section's id

  const titleDivClass = "titleDivClass";
  const tableDivClass = "tableDivClass";
  const tailDivClass = "tailDivClass";

  const theadClass = "theadClass"; //table header section's class
  const tbodyClass = "tbodyClass"; //table body section's class
  const tfootClass = "tfootClass"; //table foot section's class

  //table_id
  if (
    typeof printParam.table_id == "undefined" ||
    printParam.table_id.length < 2
  ) {
    alert("表(table_id)未指定!");
    return;
  }
  tableId = printParam.table_id;
  var div = document.getElementById(tableId);
  if (div == null) {
    alert("获取表格div失败!");
    return;
  }

  if (typeof printParam.debug == "string" && (printParam.debug == 'no' || printParam.debug == '否')) {
    debuging = 0;
  }
  //if this is an el-table?
  var elheaders = div.getElementsByClassName("el-table__header");
  if (elheaders.length > 0) eltable = 1;

  var sectionGroup = new Object();
  createAllSections(printParam, sectionGroup, eltable);
  titleDiv = sectionGroup.titleDiv;
  tableDiv = sectionGroup.tableDiv;
  tailDiv = sectionGroup.tailDiv;
  var thead = sectionGroup.thead;
  var tbody = sectionGroup.tbody;
  var tfoot = sectionGroup.tfoot;

  titleHeight = sectionGroup.titleHeight;
  tailHeight = sectionGroup.tailHeight;
  theadHeight = sectionGroup.theadHeight;
  tfootHeight = sectionGroup.tfootHeight;

  titleDiv.setAttribute("id", titleDivId);
  titleDiv.setAttribute("class", titleDivClass);
  tableDiv.setAttribute("id", tableDivId);
  tableDiv.setAttribute("class", tableDivClass);
  tailDiv.setAttribute("id", tailDivId);
  tailDiv.setAttribute("class", tailDivClass);
  thead.setAttribute("id", theadId);
  thead.setAttribute("class", theadClass);
  tbody.setAttribute("id", tbodyId);
  tbody.setAttribute("class", tbodyClass);
  tfoot.setAttribute("id", tfootId);
  tfoot.setAttribute("class", tfootClass);

  var trRow = sectionGroup.trRow;//tbody.getElementsByTagName("tr");
  if (trRow.length < 1) {
    alert("不能打印空表,至少有一空行!");
    return;
  } else if (debuging) console.log('总共 ' + trRow.length + ' 行数据.')

  //paper height
  var value = parseInt(printParam.paper_height);
  if (value == value && value >= 300) {
    paperHeight = value;
    if (titleHeight + theadHeight + tfootHeight + tailHeight > paperHeight - 100) {
      alert("纸张长度设置太小，放不下表头表尾内容...");
      return;
    }
    //else alert("按纸张长度" + paperHeight + "自动分页...")
  }
  //paper width
  var value = parseInt(printParam.paper_width);
  if (value == value && value >= 300) {
    paperWidth = value;
  } else paperWidth = 300;

  //page_rows & second_rows
  var value = parseInt(printParam.page_rows);
  if (value != value && paperHeight < 300) {
    alert("纸张长度及每页行数均未指定,将不分页打印.");
    pageRows = 0;
  } else if (value == value) {
    pageRows = value;
    if (paperHeight < 300)
      alert("将按每页" + pageRows + "行自动分页...");
  }

  secondRows = pageRows;
  if (
    typeof printParam.second_rows != "undefined" &&
    parseInt(printParam.second_rows) > 0
  ) {
    secondRows = parseInt(printParam.second_rows);
  }
  if (pageRows == 0) secondRows = 0;
  //no page break
  else if (pageRows < 0) pageRows = secondRows = 17;
  if (secondRows < 0) secondRows = pageRows;

  //color
  if (
    typeof printParam.color != "undefined" &&
    (printParam.color == "color" || printParam.color == "彩色")
  ) {
    color = 1; //keep colors
  }

  //button
  if (
    typeof printParam.button != "undefined" &&
    (printParam.button == "button" || printParam.button == "打印")
  ) {
    button = 1; //keep buttons
  }

  //blank pages?
  if (
    typeof printParam.blank != "undefined" &&
    parseInt(printParam.blank) > 0
  ) {
    blank = parseInt(printParam.blank);
  }

  //pages list
  if (
    typeof printParam.page_list != "undefined" &&
    typeof printParam.page_list == "string" &&
    printParam.page_list.length > 0
  ) {
    if (printParam.page_list != "全部") {
      var txt = printParam.page_list.split(",");
      for (var i = 0; i < txt.length; i++) {
        if (txt[i].indexOf("-") < 0) pageList.push(parseInt(txt[i]));
        else {
          var txt1 = txt[i].split("-");
          if (
            typeof txt1 != "undefined" &&
            txt1 != null &&
            txt1.length == 2
          ) {
            var min = parseInt(txt1[0]);
            var max = parseInt(txt1[1]);
            for (var j = min; j <= max; j++) pageList.push(j);
          }
        }
      }
    }
  }

  //hidden columns list
  if (
    typeof printParam.hidden_col != "undefined" &&
    typeof printParam.hidden_col == "string" &&
    printParam.hidden_col.length > 0
  ) {
    if (printParam.hidden_col != "无") {
      var txt = printParam.hidden_col.split(",");
      for (var i = 0; i < txt.length; i++) {
        if (txt[i].indexOf("-") < 0) hiddenCols.push(parseInt(txt[i]));
        else {
          var txt1 = txt[i].split("-");
          if (
            typeof txt1 != "undefined" &&
            txt1 != null &&
            txt1.length == 2
          ) {
            var min = parseInt(txt1[0]);
            var max = parseInt(txt1[1]);
            for (var j = min; j <= max; j++) hiddenCols.push(j);
          }
        }
      }
    }
  }

  // title in first page only
  if (
    typeof printParam.title != "undefined" &&
    (printParam.title == "first" || printParam.taill == "首页")
  ) {
    titleType = 1; // title only for first page
  }

  //tail in first page only?
  if (
    typeof printParam.tail != "undefined" &&
    (printParam.tail == "first" || printParam.taill == "首页")
  ) {
    tailType = 1; // tail only for first page
  }

  if (typeof printParam.preview != "undefined" && printParam.preview == "预览") {
    preview = 1;   //preview and add print buttons
  }

  //adjust columns width
  var colgroup = '-';
  var colgroups = div.getElementsByTagName("colgroup");
  var groupCols = '';
  if (typeof colgroups == "object" && colgroups.length > 0
  ) {

    groupCols = colgroups[0].getElementsByTagName("col");
    if (typeof groupCols == "object" && groupCols.length > 0) {
      var realCols = 0;  //el-table has gutter col
      for (var i = 0; i < groupCols.length; i++) {
        if (groupCols[i].getAttribute("name") == "gutter" ||
          (hiddenCols.length > 0 && hiddenCols.indexOf(i) >= 0)
        ) continue;
        realCols++;
      }

      if (typeof colWidths == "object" && colWidths.length > 0) {
        var amount = 0.0;
        var fixedCols = 0;
        for (var i = 0; i < colWidths.length; i++) {
          var col = parseInt(colWidths[i].col);
          if (groupCols[col].getAttribute("name") == "gutter" ||
            (hiddenCols.length > 0 && hiddenCols.indexOf(col) >= 0)
          ) continue;
          amount += parseInt(colWidths[i].width);
          fixedCols++;
        }

        var avg = avgWidth;

        if (paperWidth - amount > 10 && realCols > fixedCols)
          avg = (0.0 + paperWidth - amount) / (realCols - fixedCols);

        if (debuging) console.log('平均值: ' + avg);
        avgWidth = parseInt(avg);

        for (var i = 0; i < groupCols.length; i++) {
          if (groupCols[i].getAttribute("name") == "gutter" ||
            (hiddenCols.length > 0 && hiddenCols.indexOf(i) >= 0)) continue;
          groupCols[i].setAttribute("width", avgWidth);
        }
        for (var i = 0; i < colWidths.length; i++) {
          var col = parseInt(colWidths[i].col);
          var width = parseInt(colWidths[i].width);
          if (col < 0 || col >= groupCols.length || width <= 0) continue;
          if (groupCols[col].getAttribute("name") == "gutter" ||
            (hiddenCols.length > 0 && hiddenCols.indexOf(col) >= 0)) continue;
          groupCols[col].setAttribute("width", width);
        }
      }
      //if not match paper width, ajust all cols in average
      if (realCols > 0) {
        var amount = 0.0;
        for (var i = 0; i < groupCols.length; i++) {
          if (hiddenCols.length > 0 && hiddenCols.indexOf(i) >= 0
          ) continue;
          amount += parseInt(groupCols[i].getAttribute("width"));
        }
        var leftSpace = paperWidth - amount;
        var avg = parseInt((0.0 + leftSpace) / realCols);
        amount = 0;
        for (i = 0; i < groupCols.length; i++) {
          if (groupCols[i].getAttribute("name") == "gutter" ||
            (hiddenCols.length > 0 && hiddenCols.indexOf(i) >= 0)
          ) continue;
          var newWidth = parseInt(groupCols[i].getAttribute("width")) + avg;
          groupCols[i].setAttribute("width", newWidth);
          amount += newWidth;
        }
        leftSpace = paperWidth - amount;
        var cols = leftSpace >= 0 ? leftSpace : (-leftSpace);
        if (leftSpace < 0) avg = -1;
        else avg = 1;
        for (var i = 0; i < cols && i < groupCols.length; i++) {
          var newWidth = parseInt(groupCols[i].getAttribute("width")) + avg;
          groupCols[i].setAttribute("width", newWidth);
        }
      }
      if (debuging) {
        amount = 0;
        for (var i = 0; i < groupCols.length; i++) {
          console.log('第' + i + '列宽度: ' + groupCols[i].getAttribute("width"));
          if (hiddenCols.length > 0 && hiddenCols.indexOf(i) >= 0) continue;
          var avg = parseInt(groupCols[i].getAttribute("width"));
          amount += avg;

        }
        console.log('总宽度: ' + amount);
      }
      colgroup = colgroups[0];
      //remove all hidden cols
      if (eltable && hiddenCols.length > 0) {
        colgroup = document.createElement("colgroup");
        var cols = groupCols.length;
        for (var i = 0; i < cols; i++) {
          if (hiddenCols.indexOf(i) < 0) {
            var col = document.createElement('col');
            col.setAttribute('name', groupCols[i].getAttribute('name'));
            col.setAttribute('width', groupCols[i].getAttribute('width'));
            colgroup.appendChild(col);
          }
        }

      }
    } //groupcols
  } //colgroups

  //calc col indexes in el-table
  if (eltable && groupCols.length > 0) {
    var tmpThs = thead.getElementsByTagName("th");
    for (var i = 0; i < groupCols.length; i++) {
      var colName = groupCols[i].getAttribute('name');
      for (var j = 0; j < tmpThs.length; j++) {
        if (tmpThs[j].getAttribute('class').indexOf(colName) >= 0) {
          headColIndexArray[i] = j;
        }
      }
    }
  }

  thead.style.width = "100%";
  var ths = thead.getElementsByTagName("td");
  if (typeof ths == 'object' && ths.length > 0) {
    for (var i = 0; i < ths.length; i++) {

      if (!color) {
        ths[i].style.color = "black";
        ths[i].style.width = "%100";
        //ths[i].style.border = borderStyle;
        ths[i].style.background = "white";
      }

      if (hiddenCols.length > 0 && hiddenCols.indexOf(i) >= 0) {
        var j = i;
        if (eltable) {
          j = headColIndexArray[i];
        }
        ths[j].visibility = "hidden";
        ths[j].style.display = "none";
      }
    }
  }
  else {
    ths = thead.getElementsByTagName("th");
    for (var i = 0; i < ths.length; i++) {
      var classStr = ths[i].getAttribute("class");
      if (typeof classStr == "string" && classStr != null) {
        if (classStr.indexOf("gutter") >= 0) {
          ths[i].style.display = "none";
        }
      }
      if (!color) {
        ths[i].style.color = "black";
        ths[i].style.width = "%100";
        //ths[i].style.border = borderStyle;
        ths[i].style.background = "white";
      }
      if (hiddenCols.length > 0 && hiddenCols.indexOf(i) >= 0) {
        var j = i;
        if (eltable) {
          j = headColIndexArray[i];
        }
        ths[j].visibility = "hidden";
        ths[j].style.display = "none";
      }
    }
  }
  handleButtons(titleDiv, button, color);
  handleButtons(tailDiv, button, color);
  handleButtons(tbody, button, color);

  var cssContent = "<style id='html-style'>";
  cssContent += "table{table-layout: fixed;word-break: break-all; word-wrap: break-word;}";
  cssContent += handleDivStyle(titleDiv, printParam.title_font, printParam.title_font_size);
  cssContent += handleDivStyle(tailDiv, printParam.tail_font, printParam.tail_font_size);
  cssContent += handleTableStyle(thead, printParam.thead_font, printParam.thead_font_size,
    printParam.thead_line_height);
  cssContent += handleTableStyle(tbody, printParam.tbody_font, printParam.tbody_font_size,
    printParam.tbody_line_height);
  cssContent += handleTableStyle(tfoot, printParam.tfoot_font, printParam.tfoot_font_size,
    printParam.tfoot_line_height);

  cssContent += handleClassStyle(titleDivClass, printParam.title_style);
  cssContent += handleClassStyle(tailDivClass, printParam.tail_style);
  cssContent += handleClassStyle(theadClass, printParam.thead_style);
  cssContent += handleClassStyle(tbodyClass, printParam.tbody_style);
  cssContent += handleClassStyle(tfootClass, printParam.tfoot_style);
  cssContent += `table .el-table__cell.is-center{text-align:center;}table.el-table__cell.is-right{ text-align:right;}`;
  cssContent += "td{border:" + borderStyle + ";}th{border:" + borderStyle + ";font-weight:normal;}</style>";

  var rowCount = trRow.length - firstRow;

  var pages = 1;

  if (pageRows == 0) pageRows = secondRows = rowCount;
  else if (rowCount < pageRows) pages = 0;
  else pages = 1 + parseInt((rowCount - pageRows) / secondRows);

  if (blank > 0) {
    pages = blank;
    rowCount = pageRows + (pages - 1) * secondRows;
    pageList.length = 0;
  }

  //blank page line height
  if (blank > 0) {
    if (typeof printParam.blank_line_height != "undefined"
      && parseInt(printParam.blank_line_height) > 10)
      blankLineHeight = parseInt(printParam.blank_line_height);
    else blankLineHeight = trRow[0].clientHeight;

    alert("将打印 " + blankLineHeight + "页空表...");
  }
  var trClass = trRow[firstRow].getAttribute("class");
  var trStyle = trRow[firstRow].getAttribute("style");
  var trTds = trRow[firstRow].getElementsByTagName("td");

  var columns = trTds.length;

  var htmlContent = "";

  var rowIndex = firstRow;
  var outPages = 0;

  var pageHeight = 0;
  var height = 0;
  var newTableTrs = "";
  var pageFull = 0;
  var meetEnd = 0;

  //console.log(titleHeight,theadHeight,tfootHeight,tailHeight,"========");
  // 打开新页面
  var pwin = window.open("_blank", "打印预览");
  //pwin=window;

  if (pwin == null) {
    alert("打开新窗口失败，再尝试一次，如果浏览器禁止弹窗请先关掉该设置!");
    return;
  }

  var htmlStr = `<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8;'>   <title>加载中... ` +
    trRow.length + ` 行</title></head><body ondrop='drop(event)' ondragover='allowDrop(event)'>` + "</body>";

  //hxl add by========================
  htmlStr += getPrinterStyle() + cssContent + `</html>`;
  pwin.document.write(htmlStr);
  pwin.document.close();
  htmlStr = '';
  //console.log(printStr);

  var breakStr = "<div style='break-before: page;'></div>";
  var breakPageDiv = '';
  //按指定的纸张高度自动分页
  if (paperHeight >= 300) {

    //cssContent = "";

    var newPage = 1;

    //var cssStyle = pwin.document.createElement("style");
    //cssStyle.innerHTML = cssContent;
    //pwin.document.getElementsByTagName("html")[0].appendChild(cssStyle);
    if (eltable) {
      var htmlBody = pwin.document.getElementsByTagName("section")[0];
      if (typeof htmlBody != "object")
        var htmlBody = pwin.document.getElementsByTagName("body")[0];
    }
    else
      var htmlBody = pwin.document.getElementsByTagName("body")[0];

    htmlContent = "<div id='pagesDiv' style='width:" + paperWidth + "px;'>";

    var pagesDiv = pwin.document.createElement("div");

    pagesDiv.setAttribute("id", "pagesDiv");
    pagesDiv.style.width = paperWidth + "px";

    //晋城定制，两边留宽方便打印
    pagesDiv.style.paddingLeft = '30px';
    pagesDiv.style.paddingRight = '30px';

    htmlBody.appendChild(pagesDiv);

    if (blank > 0) {
      pages = blank;
      rowCount = pages * 100;
    }
    else pages = 10000;

    if (eltable) {
      var realBody = document.getElementById(tableId).getElementsByTagName("tbody")[0];
      trRow = realBody.getElementsByTagName("tr");
    } else {
      var realBody = document.getElementById(printParam.tbodyId);
      trRow = realBody.getElementsByTagName("tr");
    }

    var leftContent = 0;
    var leftTr;
    var leftContentOnly = 0;
    for (var i = 0; leftContent ||(i < rowCount && outPages < pages); i++, rowIndex++) {

      if (leftContent && (i >= rowCount || outPages >= pages)) {
        leftContentOnly = 1;
        rowIndex = rowCount - 1;
      }
      else leftContentOnly = 0;

      if (outPages > 1000) {
        pwin.alert("页数太多，中止...");
        break;
      }
      if (newPage) {

        //新一页
        var pageDiv = pwin.document.createElement("div");
        pageDiv.setAttribute("id", "第" + (outPages + 1) + "页");

        //换页
        breakPageDiv = pwin.document.createElement("div");
        if (outPages > 0) {
          breakPageDiv.innerHTML = breakStr;
        }
        pagesDiv.appendChild(breakPageDiv);
        pagesDiv.appendChild(pageDiv);

        //抬头
        var ttlDiv = pwin.document.createElement("div");
        if (titleType == 0 || (titleType == 1 && outPages != 0)) {
          //no title
        } else {
          //title
          ttlDiv.innerHTML = titleDiv.outerHTML;
        }
        pageDiv.appendChild(ttlDiv);

        //创建新的table
        var newTable = pwin.document.createElement("table");
        pageDiv.appendChild(newTable);

        newTable.setAttribute("border", borderStyle);
        newTable.style.width = "100%";
        newTable.style.borderColor = "black";
        newTable.style.boxSizing = "border-box";
        newTable.style.cellpadding = "0";
        newTable.style.cellspacing = "0";
        newTable.style.borderCollapse = "collapse";
        newTable.style.borderTop = "0px";
        newTable.style.borderLeft = "0px";
        newTable.style.borderRight = "0px";
        newTable.style.borderBottom = "0px";
        //newTable.style.borderCollapse = "separate";
        newTable.style.borderSpacing = "0px 00px";
        //newTable.style.tableLayout="fixed";
        //newTable.style.width=paperWidth+"px";

        if (colgroups.length > 0 && typeof colgroup == 'object') {
          var thisColGroup = pwin.document.createElement("colgroup");
          thisColGroup.innerHTML = colgroup.innerHTML;
          newTable.appendChild(thisColGroup);
        }
        //表头
        var newHeadTbody = pwin.document.createElement("tbody");
        newTable.appendChild(newHeadTbody);
        newHeadTbody.innerHTML = thead.innerHTML;
        newHeadTbody.setAttribute("class", theadClass);

        //表体
        var newTbody = pwin.document.createElement("tbody");
        newTable.appendChild(newTbody);
        newTbody.setAttribute("class", tbodyClass);
        newTbody.setAttribute("id", "table-" + outPages);

        //表脚
        var newFootBody = pwin.document.createElement("tbody");
        newFootBody.innerHTML = tfoot.innerHTML;
        newTable.appendChild(newFootBody);

        //表后签名栏
        var tlDiv = pwin.document.createElement("div");
        if (tailType == 0 || (tailType == 1 && outPages != 0)) {
          //no tail
        } else {
          //tail
          tlDiv.innerHTML = tailDiv.outerHTML;
        }
        pageDiv.appendChild(tlDiv);

        if (paging) {
          var pageNoDiv = pwin.document.createElement("div");
          pageNoDiv.innerHTML = PageNoDivStr(outPages + startPage);
          pageDiv.appendChild(pageNoDiv);
        }

        height = Math.ceil(parseFloat(pwin.getComputedStyle(pageDiv).height));
        //if (debuging)
        //    console.log("空表高度:" + height);

        if (leftContent) {
          leftContent = 0;
          newTbody.appendChild(leftTr);
          height = Math.ceil(parseFloat(pwin.getComputedStyle(pageDiv).height));
          if (height > paperHeight) {
            pwin.alert("不支持单行内容跨越三页，停止打印...");
            break;
          }
        }
      }

      //创建一行数据
      var newTr = pwin.document.createElement("tr");
      var tds = trRow[rowIndex].getElementsByTagName("td");
      columns = tds.length;
      if (blank > 0) {
        newTr.style.lineHeight = blankLineHeight + "px;";
      }

      var thisTd;

      if (blank < 1 && hiddenCols.length < 1) newTr.innerHTML = trRow[rowIndex].innerHTML;
      else {
        for (var n = 0; n < columns; n++) {
          thisTd = pwin.document.createElement("td");
          if (blank > 0) {
            thisTd.setAttribute("class", tds[n].getAttribute("class"));
            thisTd.setAttribute("style", tds[n].getAttribute("style"));
            if (n == columns - 1) {
              thisTd.innerHTML = "`";
              thisTd.style.textAlign = "right";
              //newTable.style.textAlign = "left";
            }
          } else thisTd.innerHTML = tds[n].innerHTML;
          if (blank < 1)
            thisTd.style.textAlign = "center";
          if (!color) {
            //thisTd.style.color = "black";
            thisTd.style.background = "white";
          }
          if (hiddenCols.length > 0 && hiddenCols.indexOf(n) >= 0) {
            thisTd.visibility = "hidden";
            thisTd.style.display = "none";
          }
          newTr.appendChild(thisTd);
        }
      }
      if (leftContentOnly == 0)
        newTbody.appendChild(newTr);

      leftContent = 0;
      var removeRow = false;
      height = Math.ceil(parseFloat(pwin.getComputedStyle(pageDiv).height));
      if (height > paperHeight) {
        if (debuging)
          console.log('第' + outPages + '页高: ' + height + ',越界');

        var startCol = 2; //these cols copy to next page if the row is divided
        var thisTds = newTr.getElementsByTagName("td");
        var txtArr = new Array();

        var tempLengthList = [];
        var allLength = 0;
        //将需要分行的列数据先保存，同时将列赋空
        for (let col of divideCols) {
          var spans = thisTds[col].getElementsByTagName("span");

          if (typeof spans == 'object' && spans.length > 0) {
            txtArr[col] = spans[0].innerText;
            spans[0].innerText = '';
          }else{
            txtArr[col] = '';
          }
        }
        //遍历每一个需要分行的列
        for(let col of divideCols){
          let tempLenth;
          let spans = thisTds[col].getElementsByTagName("span");
          if (typeof spans == 'object' && spans.length > 0) {
            spans[0].innerText = txtArr[col];
          }else{
            continue;
          }

          tempLenth = txtArr[col].length;
          height = Math.ceil(parseFloat(pwin.getComputedStyle(pageDiv).height));
          while(height > paperHeight){
            if(tempLenth <= 0) break;
            tempLenth--;
            let spans = thisTds[col].getElementsByTagName("span");
            spans[0].innerText = txtArr[col].slice(0, tempLenth);

            height = Math.ceil(parseFloat(pwin.getComputedStyle(pageDiv).height));
          }
          tempLengthList[col] = tempLenth;
          allLength += tempLenth;
        }

        if (allLength <= 0){
          removeRow = true;
        } else {
          //some content left, store it and adding to next page later
          leftTr = pwin.document.createElement("tr");
          for (var k = 0; k < thisTds.length; k++) {
            var leftTd = pwin.document.createElement("td");
            leftTd.innerHTML = thisTds[k].innerHTML;
            leftTr.appendChild(leftTd);
            var spans = leftTd.getElementsByTagName("span");
            var imgs = leftTd.getElementsByTagName("img");
            if (typeof imgs == 'object' && imgs.length > 0) {
              for (var j = 0; j < imgs.length; j++)
                imgs[j].parentNode.removeChild(imgs[j]);
            } else if (typeof spans == 'object' && spans.length > 0 && k >= startCol
            ) {
              var leftSpan = leftTd.getElementsByTagName("span")[0];
              if (divideCols.indexOf(k)>=0 && txtArr[k].length >= tempLengthList[k]){
                leftSpan.innerText = txtArr[k].slice(tempLengthList[k]);
              } else {
                leftSpan.innerText = '';
              }
            }
          }
          leftContent = 1;
        }

        /**************old version******************
         for (var k = 0; k < thisTds.length; k++) {
                    var spans = thisTds[k].getElementsByTagName("span");
                    var imgs = thisTds[k].getElementsByTagName("img");
                    if (typeof imgs == 'object' && imgs.length > 0) continue;
                    if (typeof spans == 'object' && spans.length > 0) {
                        txtArr[k] = spans[0].innerHTML.split('');
                        if (maxChCount < txtArr[k].length) maxChCount = txtArr[k].length;
                        //spans[0].innerHTML = '';
                    }
                }

         var chCount = 0;
         height = Math.ceil(parseFloat(pwin.getComputedStyle(pageDiv).height));
         if (debuging)
         console.log('清文字后页高: ' + height);
         //if it is shortter after clear text, divide the texts into two rows.
         if (height < paperHeight) {
                    while (height <= paperHeight) {
                        for (var k = 0; k < thisTds.length; k++) {
                            var spans = thisTds[k].getElementsByTagName("span");
                            var imgs = thisTds[k].getElementsByTagName("img");
                            if (typeof imgs == 'object' && imgs.length > 0) continue;
                            if (typeof spans == 'object' && spans.length > 0) {
                                if (chCount < txtArr[k].length) {
                                    spans[0].innerHTML += txtArr[k][chCount];
                                }
                            }
                        }
                        height = Math.ceil(parseFloat(pwin.getComputedStyle(pageDiv).height));
                        chCount++;
                        //console.log('adding ch', pageDiv.clientHeight);
                    }
                    height = Math.ceil(parseFloat(pwin.getComputedStyle(pageDiv).height));
                    if (height > paperHeight && chCount > 0) {
                        chCount--;
                        for (var k = 0; k < thisTds.length; k++) {
                            var spans = thisTds[k].getElementsByTagName("span");
                            var imgs = thisTds[k].getElementsByTagName("img");
                            if (typeof imgs == 'object' && imgs.length > 0) continue;
                            if (typeof spans == 'object' && spans.length > 0) {
                                if (spans[0].innerHTML.length >= chCount) {
                                    spans[0].innerHTML = spans[0].innerHTML.substr(0, chCount);
                                }
                            }
                        }
                    }

                    //some content left, store it and adding later
                    if (chCount > 0 && chCount < maxChCount) {
                        //console.log('chCount < maxChCount', pageDiv.clientHeight);
                        leftTr = pwin.document.createElement("tr");
                        for (var k = 0; k < thisTds.length; k++) {
                            var leftTd = pwin.document.createElement("td");
                            leftTd.innerHTML = thisTds[k].innerHTML;
                            leftTr.appendChild(leftTd);
                            var spans = leftTd.getElementsByTagName("span");
                            var imgs = leftTd.getElementsByTagName("img");
                            if (typeof imgs == 'object' && imgs.length > 0) {
                                for (var j = 0; j < imgs.length; j++)
                                    imgs[j].parentNode.removeChild(imgs[j]);
                            } else if (typeof spans == 'object' && spans.length > 0) {
                                var leftSpan = leftTd.getElementsByTagName("span")[0];
                                leftSpan.innerText = '';
                                for (var j = chCount; j < txtArr[k].length; j++) {
                                    leftSpan.innerText += txtArr[k][j];
                                }
                            }
                        }
                        leftContent = 1;

                    }
                    else removeRow = true;
                } else if (height == paperHeight) removeRow = true;
         ********************old version ************/
      }
      height = Math.ceil(parseFloat(pwin.getComputedStyle(pageDiv).height));
      //console.log(newTr.clientHeight, height, pageDiv.offsetHeight, pwin.getComputedStyle(pageDiv).height);

      //此行不能添加，直接分页
      if (height >= paperHeight || leftContent || removeRow) {
        pageFull = 1;
        if (height > paperHeight || removeRow) {
          newTbody.removeChild(newTr);
          //newTr.remove();
        }
        var thisTr = newTbody.getElementsByTagName("tr");
        // thisTr[thisTr.length - 1].style.color = "blue";
        var neededHeight = paperHeight - pageDiv.clientHeight;
        var oldHeight = parseInt(pwin.getComputedStyle(thisTr[thisTr.length - 1]).height);
        if (neededHeight > 3) {
          thisTr[thisTr.length - 1].getElementsByTagName('td')[0].style.lineHeight = (oldHeight + neededHeight - 3) + 'px';
        }
        if (debuging) {
          console.log('纠正后本页宽高: ' + pageDiv.clientWidth + ',' + pageDiv.clientHeight);
        }
        thisTr = null;
      }
      else pageFull = 0;
      if (rowIndex + 1 == rowCount) meetEnd = 1;
      else meetEnd = 0;

      if (pageFull || (!pageFull && meetEnd)) {
        htmlContent += breakPageDiv.outerHTML + pageDiv.outerHTML;
        /*
        pagesDiv.removeChild(pageDiv);

        pageDiv.removeChild(ttlDiv); ttlDiv.remove(); ttlDiv = null;
        pageDiv.removeChild(newTable);
        pageDiv.removeChild(tlDiv); tlDiv.remove(); tlDiv = null;

        newTable.removeChild(newHeadTbody); newHeadTbody.remove(); newHeadTbody = null;
        newTable.removeChild(newTbody); newTbody.remove(); newTbody = null;
        newTable.removeChild(newFootBody); newFootBody.remove(); newFootBody = null;
        newTable.remove(); newTable = null;
        pageDiv.remove(); pageDiv = null;
    */
        if (pageFull) {
          //left some content,goto next row,else try this row again
          if (!leftContent && height != paperHeight) {
            i--; rowIndex--;
          }
          newPage = 1;
        }
        else if (height < paperHeight && paging){
          pageDiv.removeChild(pageNoDiv);
          var spaceDiv=pwin.document.createElement("div");
          spaceDiv.style.width="100%";
          spaceDiv.style.height=""+paperHeight-height;
          pageDiv.appendChild(spaceDiv);
          pageDiv.appendChild(pageNoDiv);
        }
        newTableTrs = "";
        outPages++;
        //console.log('移除此页后宽高: ' + pagesDiv.clientWidth + ',' + pagesDiv.clientHeight);
      }
      else {
        newPage = 0;
      }
      newTr = '';
    }

    //htmlBody.removeChild(pagesDiv); pagesDiv.remove(); pagesDiv = null;
    //pwin.document.getElementsByTagName("html")[0].removeChild(cssStyle);
    //cssStyle.remove();
    htmlContent += "</div>";
  }
  //按每页行数进行分页切割
  else {
    var rowIndex = firstRow;
    var outPages = 0;
    //全部完整页
    for (var i = 0; i < pages; i++) {
      if (i == 0) var count = pageRows;
      else var count = secondRows;

      if (pageList.length > 0 && pageList.indexOf(i) < 0) {
        rowIndex += count;
        continue;
      }

      //换行符
      //var sep = pwin.document.createElement("div");
      if (outPages != 0) {
        //sep.style.pageBreakAfter = "always";
        //添加换行符调节第二页标题位置
        //var br = pwin.document.createElement("br");
        breakStr = "<div style='break-after: page;'></div>";
      } else breakStr = "";//var br = pwin.document.createElement("div");
      outPages++;

      //创建新的table
      var newTable = pwin.document.createElement("table");

      newTable.setAttribute("border", borderStyle);

      newTable.style.width = "100%";
      newTable.style.borderColor = "black";
      newTable.style.boxSizing = "border-box";
      newTable.style.cellpadding = "0";
      newTable.style.cellspacing = "0";
      newTable.style.borderCollapse = "collapse";
      newTable.style.borderTop = "0px";
      newTable.style.borderLeft = "0px";
      newTable.style.borderRight = "0px";
      newTable.style.borderBottom = "0px";

      if (colgroups.length > 0 && typeof colgroup == 'object') {
        var thisColGroup = pwin.document.createElement("colgroup");
        thisColGroup.innerHTML = colgroup.innerHTML;
        newTable.appendChild(thisColGroup);
      }

      var newTableTrs = "";

      //添加中间数据部分
      for (
        var j = 0;
        j < count && rowIndex < rowCount + firstRow;
        j++, rowIndex++
      ) {
        if (blank > 0) {
          var newTr = pwin.document.createElement("tr");
        } else {
          var tds = trRow[rowIndex].getElementsByTagName("td");
          columns = tds.length;
        }

        var thisTd;
        for (var n = 0; n < columns; n++) {
          if (blank > 0) {
            thisTd = pwin.document.createElement("td");
            thisTd.setAttribute("class", trTds[n].getAttribute("class"));
            thisTd.setAttribute("style", trTds[n].getAttribute("style"));
            if (n == columns - 1) {
              thisTd.innerHTML = "`";
              thisTd.style.textAlign = "right";
              //newTable.style.textAlign = "left";
            }
          } else thisTd = tds[n];
          if (blank < 1)
            thisTd.style.textAlign = "center";
          if (!color) {
            //thisTd.style.color = "black";
            thisTd.style.background = "white";
          }
          if (hiddenCols.length > 0 && hiddenCols.indexOf(n) >= 0) {
            thisTd.visibility = "hidden";
            thisTd.style.display = "none";
          }
          if (blank > 0) {
            newTr.appendChild(thisTd);
          }
        }

        if (blank > 0) {
          newTableTrs += newTr.outerHTML;
          newTr.remove();
        }
        else newTableTrs += trRow[rowIndex].outerHTML;
      }

      var newHeadTbody = pwin.document.createElement("tbody");
      newHeadTbody.innerHTML = thead.outerHTML;
      newHeadTbody.setAttribute("class", theadClass);

      var newTbody = pwin.document.createElement("tbody");
      newTbody.setAttribute("class", tbodyClass);
      newTbody.innerHTML = newTableTrs;
      handleTableStyle(newTbody, printParam.tbody_font,
        printParam.tbody_font_size, printParam.tbody_line_height);

      //添加表格内容
      if (colgroups.length > 0 && typeof colgroup == 'object') {
        newTable.innerHTML = colgroup.innerHTML + newHeadTbody.outerHTML + newTbody.outerHTML + tfoot.outerHTML;
      }
      else newTable.innerHTML = newHeadTbody.outerHTML + newTbody.outerHTML + tfoot.outerHTML;

      //表格内容部分div
      var newTableDiv = pwin.document.createElement("div");
      newTableDiv.setAttribute("id", "第" + (i + 1) + "页");
      if (titleType == 0 || (titleType == 1 && i != 0)) {
        newTableDiv.innerHTML = newTable.outerHTML;
      } else {
        newTableDiv.innerHTML = titleDiv.outerHTML + newTable.outerHTML;
      }

      if (tailType == 0 || (tailType == 1 && i != 0)) {
      } else {
        newTableDiv.innerHTML += tailDiv.outerHTML;
      }
      if (paging) {
        var pageNoDiv = pwin.document.createElement("div");
        pageNoDiv.innerHTML = PageNoDivStr(i + startPage);
        newTableDiv.appendChild(pageNoDiv);
      }
      //if (i != pages - 1)
      var newDiv = /*sep.outerHTML + br.outerHTML*/ breakStr + newTableDiv.outerHTML;
      //else var newDiv = newTableDiv.outerHTML;

      htmlContent += newDiv;
      newHeadTbody.remove();
      newTbody.remove();
      newTable.remove();
      newTableDiv.remove();

    }

    //最后一页
    if (
      rowIndex < rowCount + firstRow &&
      !(pageList.length > 0 && pageList.indexOf(pages) < 0)
    ) {
      //换行符

      //var sep = pwin.document.createElement("div");
      if (outPages != 0) {
        //sep.style.pageBreakAfter = "always";
        //添加换行符调节第二页标题位置
        //var br = pwin.document.createElement("br");
        breakStr = "<div style='break-after: page;'></div>";
      } else breakStr = "";//var br = pwin.document.createElement("div");

      //创建新的table
      var newTable = pwin.document.createElement("table");

      newTable.setAttribute("border", borderStyle);

      newTable.style.width = "100%";
      newTable.style.borderColor = "black";
      newTable.style.boxSizing = "border-box";
      newTable.style.cellpadding = "0";
      newTable.style.cellspacing = "0";
      newTable.style.borderCollapse = "collapse";
      newTable.style.borderTop = "0px";
      newTable.style.borderLeft = "0px";
      newTable.style.borderRight = "0px";
      newTable.style.borderBottom = "0px";

      var newTableTrs = "";

      //添加中间数据部分
      var leftItemNum = 0;

      for (; rowIndex < rowCount + firstRow; rowIndex++, leftItemNum++) {

        var tds = trRow[rowIndex].getElementsByTagName("td");
        columns = tds.length;

        var thisTd;
        for (var n = 0; n < columns; n++) {
          thisTd = tds[n];

          thisTd.style.textAlign = "center";
          if (!color) {
            //thisTd.style.color = "black";
            thisTd.style.background = "white";
          }
          if (hiddenCols.length > 0 && hiddenCols.indexOf(n) >= 0) {
            thisTd.visibility = "hidden";
            thisTd.style.display = "none";
          }

        }

        newTableTrs += trRow[rowIndex].outerHTML;
        blankLineHeight = trRow[rowIndex].clientHeight;
      }

      // 添加空行

      if (pages > 0) count = secondRows;
      else count = pageRows;

      for (; leftItemNum < count; leftItemNum++) {
        var newTr = pwin.document.createElement("tr");
        newTr.style.lineHeight = blankLineHeight + "px;";
        if (typeof trClass != "undefined") newTr.setAttribute("class", trClass);
        if (typeof trStyle != "undefined") newTr.setAttribute("style", trStyle);
        rowIndex++;

        for (var i = 0; i < columns; i++) {
          var newTd = pwin.document.createElement("td");

          newTd.setAttribute("class", trTds[i].getAttribute("class"));
          newTd.setAttribute("style", trTds[i].getAttribute("style"));
          newTd.style.textAlign = "center";

          if (!color) {
            newTd.style.color = "black";
            newTd.style.background = "white";
          }
          if (hiddenCols.length > 0 && hiddenCols.indexOf(i) >= 0) {
            newTd.visibility = "hidden";
            newTd.style.display = "none";
          }
          // if (i == 0)
          //    newTd.innerHTML = rowIndex;
          if (i == (columns - 1)) {
            newTd.innerHTML = "'";
            newTd.style.textAlign = "right";
          }
          newTr.appendChild(newTd);
        }
        newTableTrs += newTr.outerHTML;
        newTr.remove();
      }

      //完成本页
      var newHeadTbody = pwin.document.createElement("tbody");
      newHeadTbody.innerHTML = thead.outerHTML;
      newHeadTbody.setAttribute("class", theadClass);

      var newTbody = pwin.document.createElement("tbody");
      newTbody.setAttribute("class", tbodyClass);
      newTbody.innerHTML = newTableTrs;
      handleTableStyle(newTbody, printParam.tbody_font,
        printParam.tbody_font_size, printParam.tbody_line_height);

      //添加表格内容
      if (colgroups.length > 0 && typeof colgroup == 'object')
        newTable.innerHTML = colgroup.innerHTML + newHeadTbody.outerHTML + newTbody.outerHTML + tfoot.outerHTML;
      else
        newTable.innerHTML = newHeadTbody.outerHTML + newTbody.outerHTML + tfoot.outerHTML;

      //表格内容部分div
      var newTableDiv = pwin.document.createElement("div");
      newTableDiv.setAttribute("id", "第" + (i + 1) + "页");
      if (titleType == 0 || (titleType == 1 && i != 0)) {
        newTableDiv.innerHTML = newTable.outerHTML;
      } else {
        newTableDiv.innerHTML = titleDiv.outerHTML + newTable.outerHTML;
      }

      if (tailType == 0 || (tailType == 1 && i != 0)) {
      } else {
        newTableDiv.innerHTML += tailDiv.outerHTML;
      }
      if (paging) {
        var pageNoDiv = pwin.document.createElement("div");
        pageNoDiv.innerHTML = PageNoDivStr(i + startPage);
        newTableDiv.appendChild(pageNoDiv);
      }
      htmlContent +=  /*sep.outerHTML + br.outerHTML*/breakStr + newTableDiv.outerHTML;

      newHeadTbody.remove();
      newTbody.remove();
      newTable.remove();
      newTableDiv.remove();
      //sep.remove();
      // br.remove();
    }
  }

  const tabStyle = `<style> *{padding: 0px,4px;margin: 4px;}
        table{width:100%;display:table-cell!important;box-sizing:border-box;}
        .el-table__header,.el-table__body,.el-table__footer{width:100%!important;border-collapse: collapse;text-align:center;}
        table,table tr th, table tr td { border:1px solid #091020;border-collapse: collapse;color:black;word-wrap:break-word}
        table tr th,table tr td{padding:4mm 0mm;word-wrap:break-word }
        .el-table__body, tr td .cell{width:100%!important}
        .el-table th.gutter{display: none;}
        .el-table colgroup.gutter{display: none;}</style>
        `;


  pwin.document.getElementsByTagName('title')[0].innerText = '`';

  titleDiv.remove();
  tableDiv.remove();
  thead.remove();
  //tbody.remove();
  tfoot.remove();
  tailDiv.remove();

  if (paperHeight < 300) //not break page by paper height
  {
    //完成完整页面
    let printStr =
      "<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8;'>   <title>'</title></head>";

    var printerStyle = getPrinterStyle(printParam);

    printStr += "<body ondrop='drop(event)' ondragover='allowDrop(event)'>" +
      htmlContent + "</body>" + printerStyle + cssContent + "</html>";
    htmlContent = ""; htmlContent = null;

    //var pwin = window.open("_blank", "打印预览");
    // 将内容赋值到新页面
    pwin.document.write(printStr);
    //console.log(pwin.document.getElementsByTagName("html")[0]);
    pwin.document.close();

    printStr = ''; printStr = null;
  }
  if (!preview) {
    pwin.document.getElementById('btns').style.display = 'none';
    pwin.document.title = "打印预览, " + outPages + ' 页';
    // 聚焦-不加focuse，在某些情况下，打印页面会有问题。
    pwin.focus();
    // 使用setTimeout，等页面dom元素渲染完成后再打印。
    setTimeout(function () {
      pwin.print(); // 打印功能。 例如 window.print() 直接打印当前整个页面。
      pwin.close(); // 关闭 打印创建的当前页面
      //window.location.reload();
    }, 800);
  }
}

function createAllSections(printParam, sectionGroup, eltable) {
  var heightObj = new Object();
  heightObj.height = 0;

  //减少内存开销，不创建新组件
  sectionGroup.tableDiv = createSection("", heightObj);

  sectionGroup.titleDiv = createSection(printParam.title_id, heightObj);
  sectionGroup.titleHeight = heightObj.height;

  sectionGroup.tailDiv = createSection(printParam.tail_id, heightObj);
  sectionGroup.tailHeight = heightObj.height;

  if (eltable) {

    var thead = document.createElement("thead");
    thead.innerHTML = document.getElementById(printParam.table_id).getElementsByTagName("thead")[0].innerHTML;
    var theadHeight = document.getElementById(printParam.table_id).getElementsByTagName("thead")[0].clientHeight;

    var ths=thead.getElementsByTagName("th");
    for( var i=0;i<ths.length;i++) {
      ths[i].setAttribute("class",ths[i].getAttribute("class")+" theadClass");
    }

    //减少内存开销，不创建新组件，直接引用
    //var tbody = document.createElement("tbody");
    //tbody.innerHTML = document.getElementById(printParam.table_id).getElementsByTagName("tbody")[0].innerHTML;

    var tbody = document.getElementById(printParam.table_id).getElementsByTagName("tbody")[0];
    var trRow = tbody.getElementsByTagName("tr");

    var tfoot = createSection("", heightObj);
    var tfootHeight = 0;
  }
  else {
    var thead = createSection(printParam.table_head, heightObj);
    var theadHeight = heightObj.height;

    //var tbody = createSection(printParam.table_body, heightObj);
    var tbody = document.getElementById(printParam.table_body);
    if (tbody != "object") tbody = document.createElement("div");
    var trRow = tbody.getElementsByTagName("tr");
    var tfoot = createSection(printParam.table_foot, heightObj);
    var tfootHeight = heightObj.height;
  }

  sectionGroup.thead = thead;
  sectionGroup.theadHeight = theadHeight;

  sectionGroup.tbody = tbody;
  sectionGroup.trRow = trRow;

  sectionGroup.tfoot = tfoot;
  sectionGroup.tfootHeight = tfootHeight;

}
//copy a div and return the new one
function createSection(sectionId, heightObj) {
  heightObj.height = 0;

  if (
    typeof sectionId != "string" ||
    sectionId.length < 2
  ) {
    return document.createElement("div");
  }

  var div = document.getElementById(sectionId);
  if (div == null) return document.createElement("div");
  var headTag = div.tagName;
  if (headTag == null) {
    return document.createElement("div");
  }
  else {
    var section = document.createElement(headTag);
    section.innerHTML = div.innerHTML;
    section.setAttribute("id", sectionId);
    section.setAttribute("class", div.getAttribute("class"));
    section.setAttribute("style", div.getAttribute("style"));
    heightObj.height = div.clientHeight;

    return section;
  }

}

function handleButtons(thisDiv, button, color) {
  if (typeof thisDiv == "undefined") return;
  var buttons = thisDiv.getElementsByTagName("button");
  for (var i = 0; i < buttons.length; i++) {
    if (!button) buttons[i].style.visibility = "hidden";
    if (!color) {
      buttons[i].style.color = "black";
      buttons[i].style.background = "white";
    }
  }
}
function handleClassStyle(className, styleString) {

  if (typeof className != "string" || typeof styleString != "string") return "";
  if (className.length < 4 || styleString.length < 4) return "";
  var css = " ." + className + "{ " + styleString + "} ";
  return css;
}
//set font-size and return css content
function handleDivStyle(thisDiv, fontFamily, fontSize) {
  if (typeof thisDiv == "undefined") return "";
  var className = thisDiv.getAttribute("class");
  if (typeof fontSize != "undefined" && parseInt(fontSize) > 1) {
    var size = parseInt(fontSize) + "px";

    thisDiv.style.fontSize = size;
    var items = thisDiv.getElementsByTagName("span");
    for (var i = 0; i < items.length; i++) {
      //items[i].style.fontSize = size;
      var className = items[i].getAttribute("class");
      if (className == null) className = thisDiv.getAttribute("class");
      else className += "   " + thisDiv.getAttribute("class");
      items[i].setAttribute("class", className);
    }
  }
  if (typeof fontFamily == "string" && fontFamily.length > 1) {

    if (className != null) {
      var css = " ." + className + "{font-family:" + "'" + fontFamily + "'} ";
      return css;
    }
  }
  return "";
}
//set font-size and return css content
function handleTableStyle(thisTable, fontFamily, fontSize, lineHeight) {

  if (typeof thisTable == "undefined") return "";
  var className = thisTable.getAttribute("class");
  var items = thisTable.getElementsByTagName("tr");

  if (className != null) {
    for (var i = 0; i < items.length; i++) {
      var trClass = items[i].getAttribute("class");

      if (trClass != null) trClass += "  " + className;
      else trClass = className;
      items[i].setAttribute("class", trClass);
    }
  }
  if (typeof lineHeight != "undefined" && parseInt(lineHeight) > 1) {


    var size = parseInt(lineHeight) + "px";
    if (thisTable.getAttribute("style") == null)
      thisTable.setAttribute("style", "line-height:" + size);
    else thisTable.style.lineHeight = size;


    var items = thisTable.getElementsByTagName("tr");
    for (var i = 0; i < items.length; i++) {
      items[i].style.height = size;
    }
  }
  if (typeof fontSize != "undefined" && parseInt(fontSize) > 1) {

    var size = parseInt(fontSize) + "px";
    thisTable.style.fontSize = size;

    var items = thisTable.getElementsByTagName("th");
    for (var i = 0; i < items.length; i++) {
      items[i].style.fontSize = size;
    }
    items = thisTable.getElementsByTagName("td");
    for (var i = 0; i < items.length; i++) {
      items[i].style.fontSize = size;
    }
  }
  if (typeof fontFamily == "string" && fontFamily.length > 1) {

    if (className != null) {
      var css = " ." + className + "{font-family:" + "'" + fontFamily + "'} ";
      return css;
    }
  }
  return "";
}
function getPrinterStyle(printParam) {

  if (typeof printParam == "undefined") return "";

  var printerStyle = "<style>@media print{ th{";

  if ((typeof printParam.th_font_size == "string" || typeof printParam.th_font_size == "number")
    && parseInt(printParam.th_font_size) > 2) {
    printerStyle += "font-size:" + parseInt(printParam.th_font_size) + "px;";
  }
  if ((typeof printParam.th_line_height == "string" || typeof printParam.th_line_height == "number")
    && parseInt(printParam.th_line_height) > 2) {
    printerStyle += "line-height:" + parseInt(printParam.th_line_height) + "px;";
  }
  if (typeof printParam.th_font != "undefined" && typeof printParam.th_font == "string"
    && printParam.th_font.length > 1) {
    printerStyle += "font-family:'" + printParam.th_font + "'";
  }
  printerStyle += "}  td{";

  if ((typeof printParam.td_font_size == "string" || typeof printParam.td_font_size == "number")
    && parseInt(printParam.td_font_size) > 2) {
    printerStyle += "font-size:" + parseInt(printParam.td_font_size) + "px;";
  }
  if ((typeof printParam.td_line_height == "string" || typeof printParam.td_line_height == "number")
    && parseInt(printParam.td_line_height) > 2) {
    printerStyle += "line-height:" + parseInt(printParam.td_line_height) + "px;";
  }

  if (typeof printParam.td_font != "undefined" && typeof printParam.td_font == "string"
    && printParam.td_font.length > 1) {
    printerStyle += "font-family:`" + printParam.td_font + "`";
  }
  printerStyle += "} </style>";

  printerStyle = ""; //font-family因为引号无法正确设置，放弃不用

  return printerStyle;
}
function PageNoDivStr(page) {
  var pageNoStr = "<div style='text-align:center;position:relative;font-size:14px;height:24px;'><span id='page:"+page+"' style='position: absolute; bottom: 0px;'>—&nbsp;第&nbsp;&nbsp;";
  pageNoStr += page;
  pageNoStr += "&nbsp;&nbsp;页&nbsp; —</span></div>";
  return pageNoStr;
}
